package com.huixuebao.common.util;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * TODO
 *
 * @author yufatao
 * @version 1.0
 * @date 2020-11-01 20:03
 */
@Slf4j
public class AESEncrypt {
    private static final String KEY_AES = "AES";
    private static final String CHARSET = "UTF-8";
    private static final String KEY_MD5 = "MD5";

    public static void main(String[] args) throws Exception {
        String key = "123456";
        String encryptData = encrypt("hello world", key);
        String decryptData = decrypt(encryptData, key);
        log.info(keyRandomGenerate());
    }


    public static String keyRandomGenerate() throws NoSuchAlgorithmException {
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        SecretKey key = keygen.generateKey();
        return Base64.encodeBase64String(key.getEncoded());
    }

    // 加密
    public static String encrypt(String data, String key) {
        return doAES(data, key, Cipher.ENCRYPT_MODE);
    }

    // 解密
    public static String decrypt(String data, String key) {
        return doAES(data, key, Cipher.DECRYPT_MODE);
    }

    private static String doAES(String data, String key, int mode) {
        try {
            if (StrUtil.isBlank(data) || StrUtil.isBlank(key)) {
                return null;
            }
            boolean encrypt = mode == Cipher.ENCRYPT_MODE;
            byte[] content;
            if (encrypt) {
                content = data.getBytes(CHARSET);
            } else {
                content = Base64.decodeBase64(data);
            }
            MessageDigest md5Digest = MessageDigest.getInstance(KEY_MD5);
            SecretKeySpec keySpec = new SecretKeySpec(md5Digest.digest(key.getBytes(CHARSET)), KEY_AES);
            Cipher cipher = Cipher.getInstance(KEY_AES); // 创建密码器
            cipher.init(mode, keySpec); // 初始化
            byte[] result = cipher.doFinal(content);
            if (encrypt) {
                return Base64.encodeBase64String(result);
            } else {
                return new String(result, CHARSET);
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



}
